import React, { useEffect, useRef, useState } from 'react';
import { ErrorBoundary } from 'web-component';

const ErrorComponent = () => {
  const [error, setError] = useState(false);
  useEffect(() => {
    if (error) {
      throw new TypeError('test');
    }
  }, [error]);
  return (
    <div>
      <button
        onClick={() => {
          setError(true);
        }}
      >
        报错
      </button>
    </div>
  );
};

export default () => {
  const Ref = useRef(null);
  return (
    <ErrorBoundary
      ref={Ref}
      fallbackHolder={<div>错误兜底</div>}
      onError={(error, stack) => {
        alert(error.message);
        console.log(stack);
      }}
    >
      <button
        onClick={() => {
          if (Ref && Ref.current) {
            (Ref.current as any).triggerError(new Error('error1'), 'error1');
          }
        }}
      >
        主动触发错误
      </button>
      <ErrorComponent />
    </ErrorBoundary>
  );
};
